/*
 * XmlTransformer.java is part of htn-core.
 *
 * XmlTransformer.java is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XmlTransformer.java is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XmlTransformer.java.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.htn.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class XmlTransformer {
	
	public String toXmlString(Document doc)
	throws XmlTransformerException {
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
		StringWriter writer = new StringWriter();
		try {
			out.output(doc,writer);
		} catch (IOException ioe) {
			throw new XmlTransformerException(ioe);
		}
		return writer.toString();
	}
	
	public Document toDocument(String xml)
	throws XmlTransformerException {
		return toDocument(xml,false);
	}

	public Document toDocument(String xml, boolean validate)
	throws XmlTransformerException {
		Document xmlDoc = null;
		StringReader reader = new StringReader(xml);
		try {
			SAXBuilder sb = new SAXBuilder();
//			sb.setValidation(validate);
//			sb.setFeature("http://apache.org/xml/features/validation/schema",true);
//			sb.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation","http://www.ivoa.net/xml/VOEvent/VOEvent-v1.1.xsd");
			xmlDoc = sb.build(reader);
		} catch (JDOMException jde) {
			throw new XmlTransformerException(jde);
		} catch (IOException ioe) {
			throw new XmlTransformerException(ioe);
		}
		return xmlDoc;
	}
	
}
